package org.genntii.smcommon.utils;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.genntii.smcommon.config.ErrorMessageConfiguration;
import org.genntii.smcommon.config.ExpiredExchangeConfiguration;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;

import java.util.UUID;

@Slf4j
@RequiredArgsConstructor
public class RabbitMQUtils {

    private final RabbitTemplate rabbitTemplate;

    private final Integer maxRetries = 3;

    public void sendMessage(String exchange, String routingKey, Object msg){
        log.debug("发送消息, exchange:{}, routingKey:{}, msg:{}", exchange, routingKey, msg);
        rabbitTemplate.convertAndSend(exchange, routingKey, msg);
    }

    public void sendDelayMessage(Object msg, int delay){
        // 死信交换机延迟消息实现
        // 死信交换机队列 ErrorMessageConfiguration.ErrorMessageQueue
        log.debug("发送延迟消息, msg: {}, delay: {}ms", msg, delay);
        rabbitTemplate.convertAndSend(ExpiredExchangeConfiguration.EXPIRED_EXCHANGE, ErrorMessageConfiguration.errorRoutingKey, msg, message -> {
            message.getMessageProperties().setExpiration(String.valueOf(delay));
            return message;
        });
    }

    public void sendMessageWithConfirm(String exchange, String routingKey, Object msg){

        log.debug("发送消息, exchange:{}, routingKey:{}, msg:{}", exchange, routingKey, msg);
        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
        rabbitTemplate.convertAndSend(exchange, routingKey, msg, correlationData);
    }
}